package com.roy.springboot.security;

import com.roy.springboot.security.oauth2.config.CustomerUserDetails;
import com.roy.springboot.security.oauth2.entities.Role;
import com.roy.springboot.security.oauth2.entities.User;
import com.roy.springboot.security.oauth2.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;

/**
 * Hello world!
 */
@SpringBootApplication
public class Oauth2Application {
    public static void main(String[] args) {
        SpringApplication.run(Oauth2Application.class, args);
    }

    @Autowired
    public void authenticationManager(AuthenticationManagerBuilder builder, UserRepository userRepository) throws Exception {
        if ( userRepository.count() == 0 ) {
            userRepository.save(new User("user", "user", Arrays.asList(new Role("管理员"), new Role("USER"), new Role("ACT"))));
            userRepository.save(new User("monitor", "monitor", Arrays.asList(new Role("ACTUATOR"))));
            userRepository.save(new User("anon", "anon", Arrays.asList(new Role("anon"))));
        }
        builder.userDetailsService(new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                User user = userRepository.findByUsername(s);
                return new CustomerUserDetails(user);
            }
        });

//        builder.

//        builder.userDetailsService( s -> new CustomerUserDetails(repo.findByUsername(s)));
    }
}
